package com.example.jetty.demo.config;

import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JettyConfig {

    @Value("${server.ssl.key-store:classpath:ssl.keystore}")
    private String path;
    @Value("${server.ssl.key-store-password:123456}")
    private String password;
    @Value("${server.port:8443}")
    private int port;

    @Value("${server.jetty.thread-idle-timeout:60000}")
    private int timeout;
    @Value("${server.jetty.max-threads:200}")
    private int maxThreads;
    @Value("${server.jetty.max-threads:10}")
    private int minThreads;


    /**
     * 通过构造工厂造1个jetty
     */
    @Bean
    public ServletWebServerFactory servletContainer() {
        JettyServletWebServerFactory container = new JettyServletWebServerFactory();
        container.addServerCustomizers((Server server) -> {
            //配置线程
            final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
            //默认最大线程连接数
            threadPool.setMaxThreads(maxThreads);
            //默认最小线程连接数
            threadPool.setMinThreads(minThreads);
            //默认线程最大空闲时间60000ms
            threadPool.setIdleTimeout(timeout);

            // 添加HTTP配置
            ServerConnector connector = new ServerConnector(server);
            connector.setPort(80);

            // 添加HTTPS配置
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStorePath(path);
            sslContextFactory.setKeyStorePassword(password);

            HttpConfiguration config = new HttpConfiguration();
            config.setSecureScheme(HttpScheme.HTTPS.asString());
            config.addCustomizer(new SecureRequestCustomizer());

            ServerConnector sslConnector = new ServerConnector(
                server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(config));
            sslConnector.setPort(443);
            server.setConnectors(new Connector[]{connector, sslConnector});
        });
        return container;
    }


}
